import "dart:convert";

import "package:ct_pa_majordomo/pages/mine/withdraw/api.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:flutter/material.dart";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";

class WithdrawListPage extends StatefulWidget {
  const WithdrawListPage({super.key});

  @override
  State<WithdrawListPage> createState() => _WithdrawListPageState();
}

class _WithdrawListPageState extends State<WithdrawListPage> {
  final ScrollController _scrollController = ScrollController();
  final Map<String, dynamic> _filter = {
    "pageNum": 1,
    "pageSize": 10,
    "apartmentId": 0,
  };
  int _apartmentId = -1;

  List _withdrawList = [];
  int _total = 0;
  bool _isLoading = false;
  bool _hasMore = true;
  bool _disposed = false;

  @override
  void initState() {
    super.initState();
    
    String apartment = storage.getString("apartment") ?? "";
    if (apartment != "") {
      _apartmentId = jsonDecode(apartment)["apartmentId"] ?? -1;
    }
    
    if (_apartmentId > 0) {
      _filter["apartmentId"] = _apartmentId;
      _loadWithdrawList();
    } else {
      _hasMore = false;
    }
    
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _disposed = true;
    _scrollController.dispose();
    super.dispose();
  }

  // 加载提现申请列表
  void _loadWithdrawList() {
    if (_apartmentId <= 0 || _disposed) {
      setState(() {
        _isLoading = false;
        _hasMore = false;
      });
      return;
    }
    
    setState(() {
      _isLoading = true;
    });
    
    withdrawApi.withdrawList(_filter).then((value) {
      if (mounted && !_disposed) {
        setState(() {
          _isLoading = false;
          List newList = value["rows"] ?? [];
          print(newList);
          if (_filter["pageNum"] == 1) {
            _withdrawList = newList;
          } else {
            _withdrawList.addAll(newList);
          }
          _total = value["total"] ?? 0;
          _hasMore = _withdrawList.length < _total;
        });
      }
    }).catchError((error) {
      if (mounted && !_disposed) {
        setState(() {
          _isLoading = false;
          if (_filter["pageNum"] > 1) {
            _filter["pageNum"] = _filter["pageNum"] - 1;
          }
        });
      }
    });
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    if (_apartmentId <= 0 || _disposed) {
      return;
    }
    
    setState(() {
      _filter["pageNum"] = 1;
      _total = 0;
      _withdrawList.clear();
      _hasMore = true;
    });
    await Future.delayed(const Duration(milliseconds: 500));
    _loadWithdrawList();
  }

  // 上拉加载更多
  void _onScroll() {
    if (!mounted || _disposed || _apartmentId <= 0) return;
    
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 100) {
      if (_hasMore && !_isLoading) {
        Future.delayed(const Duration(milliseconds: 100), () {
          if (mounted && !_disposed && _hasMore && !_isLoading && _apartmentId > 0) {
            _loadMore();
          }
        });
      }
    }
  }

  void _loadMore() {
    if (!_hasMore || _isLoading || _disposed || _apartmentId <= 0) return;
    
    setState(() {
      _filter["pageNum"] = _filter["pageNum"] + 1;
    });
    
    _loadWithdrawList();
  }

  // 获取状态文本
  String _getStatusText(Map<String, dynamic> withdraw) {
    // 有三个字段代表状态，status，auditStatus，paymentStatus， 0代表未处理，1代表处理完成，2代表处理失败
    if (withdraw["paymentStatus"] == "1") {
      return "已完成";
    } else if (withdraw["paymentStatus"] == "2") {
      return "提现失败";
    } else {
      if (withdraw["auditStatus"] == "1") {
        return "审核通过";
      } else if (withdraw["auditStatus"] == "2") {
        return "审核拒绝";
      } else {
        return "审核中";
      }
    }
  }

  // 获取状态颜色
  Color _getStatusColor(String status) {
    switch (status) {
      case "审核中":
        return ThemeVars.colorWarning;
      case "审核通过":
        return ThemeVars.colorSuccess;
      case "审核拒绝":
        return ThemeVars.colorError;
      case "提现失败":
        return ThemeVars.colorError;
      default:
        return ThemeVars.colorTextSec;
    }
  }

  // 跳转到详情页
  void _goToDetail(int withdrawId) {
    Stacker.pushNamed(Keys.WITHDRAW_DETAIL, arguments: {"withdrawId": withdrawId});
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "提现申请记录",
      child: RefreshIndicator(
        onRefresh: _onRefresh,
        child: ListView(
          controller: _scrollController,
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          children: [
            if (_withdrawList.isEmpty)
              Container(
                padding: const EdgeInsets.all(40),
                child: Center(
                  child: Column(
                    children: [
                      Icon(
                        _isLoading ? Icons.hourglass_empty : Icons.receipt_long,
                        size: 48,
                        color: ThemeVars.colorTextTer,
                      ),
                      const SizedBox(height: 16),
                      Text(
                        _apartmentId <= 0 
                          ? "无效的公寓ID"
                          : _isLoading 
                            ? "加载中..."
                            : "暂无提现申请记录",
                        style: const TextStyle(
                          color: ThemeVars.colorTextSec,
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            else
              ..._withdrawList.map((withdraw) => _buildWithdrawItem(withdraw)),
            
            // 加载更多指示器
            if (_isLoading)
              const Padding(
                padding: EdgeInsets.all(16),
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              ),
            
            // 没有更多数据提示
            if (!_hasMore && _withdrawList.isNotEmpty)
              const Padding(
                padding: EdgeInsets.all(16),
                child: Center(
                  child: Text(
                    "没有更多数据了",
                    style: TextStyle(
                      color: ThemeVars.colorTextSec,
                      fontSize: 14,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  // 构建提现申请项
  Widget _buildWithdrawItem(Map<String, dynamic> withdraw) {
    return GestureDetector(
      onTap: () => _goToDetail(withdraw["withdrawId"]),
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: ThemeVars.colorBorder,
            width: 0.5,
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "提现申请 #${withdraw["withdrawId"]}",
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  decoration: BoxDecoration(
                    color: _getStatusColor(_getStatusText(withdraw)).withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    _getStatusText(withdraw),
                    style: TextStyle(
                      fontSize: 12,
                      color: _getStatusColor(_getStatusText(withdraw)),
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Text(
                  "申请金额：",
                  style: const TextStyle(
                    fontSize: 14,
                    color: ThemeVars.colorTextSec,
                  ),
                ),
                const SizedBox(width: 12),
                Text(
                  "¥${Utils.formatCurrency(withdraw["amount"] ?? 0)}",
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: ThemeVars.colorSuccess,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 4),
            Row(
              children: [
                Text(
                  "申请时间：",
                  style: const TextStyle(
                    fontSize: 14,
                    color: ThemeVars.colorTextSec,
                  ),
                ),
                const SizedBox(width: 12),
                Text(
                  withdraw["applyTime"] ?? "",
                  style: const TextStyle(
                    fontSize: 14,
                    color: ThemeVars.colorTextSec,
                  ),
                ),
              ],
            ),
            if (withdraw["paymentTime"] != null && withdraw["paymentTime"] != "") ...[
              const SizedBox(height: 4),
              Row(
                children: [
                  Text(
                    "完成时间：",
                    style: const TextStyle(
                      fontSize: 14,
                      color: ThemeVars.colorTextSec,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    withdraw["paymentTime"],
                    style: const TextStyle(
                      fontSize: 14,
                      color: ThemeVars.colorTextSec,
                    ),
                  ),
                ],
              ),
            ],
          ],
        ),
      ),
    );
  }
} 